<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属站点" prop="deptId" style="width: 90%;">
            <el-tree-select
              v-model="queryParams.deptId"
              :data="deptOptions"
              :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
              value-key="deptId"
              placeholder="请选择所属站点"
              check-strictly
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标题" prop="title" style="width: 90%;">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入标题"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['partybuilding:News:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" @handleQuery="handleQuery" @resetQuery="resetQuery"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="newsList" @selection-change="handleSelectionChange">
      <el-table-column label="所属栏目" align="center" prop="typeName" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="设为幻灯" align="center" prop="isscroll" >
        <template #default="scope">
          {{ scope.row.isscroll === 1? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="作者" align="center" prop="author" />
      <el-table-column label="发布时间" align="center" prop="releaseTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.releaseTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['partybuilding:News:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['partybuilding:News:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资讯新闻对话框 -->
    <el-dialog :title="title" v-model="open" width="57%" append-to-body style="margin-top: 9px!important;">
      <el-form ref="NewsRef" :model="form" :rules="rules" label-width="109px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属站点:" prop="deptId" style="width: 100%;">
              <el-tree-select
                v-model="form.deptId"
                :data="deptOptions"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                value-key="deptId"
                placeholder="请选择所属站点"
                check-strictly
                @change="handleDeptChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="栏目" prop="typeId">
              <el-tree-select
                v-model="form.typeId"
                :data="columnTypeOptions"
                :props="{ value: 'id', label: 'name', children: 'children' }"
                value-key="id"
                placeholder="请选择栏目"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="form.author" placeholder="请输入作者" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布时间" prop="releaseTime">
              <el-date-picker clearable
                v-model="form.releaseTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择发布时间"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="副标题" prop="subtitle">
              <el-input v-model="form.subtitle" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否幻灯" prop="isscroll">
              <el-radio-group v-model="form.isscroll">
                <el-radio v-for="dict in pb_isscroll_dict" 
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value">
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否原创" prop="isOriginal">
              <el-radio-group v-model="form.isOriginal">
                <el-radio v-for="dict in pb_isoriginal_dict" 
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value">
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="热度" prop="hot">
              <el-input-number v-model="form.hot" :min="0" placeholder="请输入热度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否外部跳转" prop="showType">
              <el-radio-group v-model="form.showType">
                <el-radio v-for="dict in pb_showType_dict" 
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value">
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="封面图片" prop="imgs">
              <image-upload
                  v-model="form.imgs"
                  :multiple="true"
                  :limit="10"
                  :suggestSize="'530*380'"
                  :file-type="['jpg', 'png', 'jpeg']"
                  :file-size="200">
              </image-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="资讯材料" prop="files">
              <file-upload
                    v-model="form.files"
                    :multiple="true"
                    :limit="10"
                    :file-type="['doc', 'docx', 'pdf']"
                    :file-size="200">
                </file-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容" style="width: 100%;">
              <editor v-model="form.content" :height="600"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="News">
import { listNews, getNews, delNews, addNews, updateNews } from "@/api/partybuilding/News";
import { listNewsType } from "@/api/partybuilding/NewsType";
import { getUserProfile } from "@/api/system/user";
import { listOrg } from "@/api/partybuilding/Org";
const baseUrl = import.meta.env.VITE_SITE_SIGN_URL;
const { proxy } = getCurrentInstance();
const newsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const typeIdList = ref([]);
const deptOptions = ref([]);
const columnTypeOptions = ref([]);
const newsTypeList = ref([]);
const userInfo = ref({}); //用户信息
const pb_isoriginal_dict = ref([{label: '是', value: '0'}, {label: '否', value: '1'}]);// 是否原创：0是，1否
const pb_isscroll_dict = ref([{label: '是', value: '0'}, {label: '否', value: '1'}]);// 是否幻灯：0是，1否
const pb_showType_dict = ref([{label: '页面', value: '0'}, {label: '外部跳转', value: '1'}]);//展示方式：0页面，1外部跳转

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    deptId: null,
    typeIds: null,
    hopt: null
  },
  rules: {
    title: [
      { required: true, message: "标题不能为空", trigger: "blur" }
    ],
    typeId: [
      { required: true, message: "栏目不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 获取用户信息
function getUserInfo() {
  getUserProfile().then((res) => {
    userInfo.value = res.data;
  });
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  listOrg().then(response => {
    deptOptions.value = proxy.handleTree(response.rows, "deptId");
    if (deptOptions.value!=null && deptOptions.value.length>0){
      queryParams.value.deptId = deptOptions.value[0].deptId;
    }
  });
};

/** 切换所属站点时，重新获取栏目下拉树结构 */
function handleDeptChange(deptId) {
  form.value.typeId = null;
  getColumnTypeTree(deptId);
}


/** 查询栏目下拉树结构 */
function getColumnTypeTree(deptIdValue) {
  let param = {
    pageNum: 1,
    pageSize: 999,
    deptId: deptIdValue
  };
  listNewsType(param).then(response => {
    newsTypeList.value = response.rows;
    columnTypeOptions.value = proxy.handleTree(response.rows);
  });
};

/** 查询资讯新闻列表 */
function getList() {
  loading.value = true;
  queryParams.value.typeIds = typeIdList.value? typeIdList.value.join(",") : null;
  listNews(queryParams.value).then(response => {
    newsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    subtitle: null,
    typeId: null,
    source: null,
    isOriginal: null,
    imgs: null,
    showType: null,
    files: null,
    content: null,
    releaseTime: null,
    author: null,
    deptId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  typeIdList.value = [];
  proxy.resetForm("NewsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  typeIdList.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 获取当前时间
function formattedTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.deptId = queryParams.value.deptId;
  getColumnTypeTree(form.value.deptId);
  form.value.content = '<p></p>';
  form.value.releaseTime = formattedTime();
  open.value = true;
  title.value = "添加资讯新闻";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getNews(_id).then(response => {
    form.value = response.data;
    if (form.value.showType!=null){
      form.value.showType = form.value.showType === 1 ? '1' : '0';
    }
    if (form.value.isOriginal!=null){
      form.value.isOriginal = form.value.isOriginal === 1 ? '1' : '0';
    }
    if (form.value.isscroll!=null){
      form.value.isscroll = form.value.isscroll === 1 ? '1' : '0';
    }
    form.value.content = form.value.content? form.value.content : '<p></p>';
    getColumnTypeTree(form.value.deptId);
    open.value = true;
    title.value = "修改资讯新闻";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["NewsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateNews(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addNews(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除资讯新闻编号为"' + _ids + '"的数据项？').then(function() {
    return delNews(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('partybuilding/News/export', {
    ...queryParams.value
  }, `News_${new Date().getTime()}.xlsx`)
}



/** 预览按钮操作 */
function handlePreview() {
  window.open(baseUrl);
}

getUserInfo();
getDeptTree();
setTimeout(() => {
  getList();
}, 100);
</script>